import { defineStore } from "pinia";
import { computed, ref } from "vue";
import { addCartAPI, delCartAPI, getCartListAPI } from "@/apis/cart";
import { useUserStore } from "./user";
export const useCartStore = defineStore('cart', () => {
  const userStore = useUserStore()
  const isLogin = computed(() => userStore.userInfo.token)
  const cartList = ref([])
  const updateNewList = async () => {
    const res = await getCartListAPI()
    cartList.value = res.result
  }
  const addCart = async (goods) => {
    if (isLogin.value) {
      await addCartAPI(goods.skuId, goods.count)
      updateNewList()
    } else {
      const item = cartList.value.find(item => item.skuId === goods.skuId)
      if (item) {
        item.count += goods.count
      } else {
        cartList.value.push(goods)
      }
    }
  }
  const delCart = async (skuId) => {
    if (isLogin.value) {
      await delCartAPI([skuId])
      updateNewList()
    } else {
      const idx = cartList.value.findIndex(item => item.skuId === skuId)
      cartList.value.splice(idx, 1)
    }
  }
  const clearCart = () => {
    cartList.value = []
  }
  //单选功能
  const singleCheck = (select, skuId) => {
    const item = cartList.value.find(item => item.skuId === skuId)
    item.selected = select
  }
  // 全选控制单选
  const allCheck = (select) => {
    cartList.value.forEach(item => item.selected = select)
  }
  // 已选中商品的数量
  const allCheckCount = computed(() => cartList.value.filter(item => item.selected).reduce((sum, i) => sum + i.count, 0))
  // 已选中商品的总价
  const allCheckPrice = computed(() => cartList.value.filter(item => item.selected).reduce((sum, i) => sum + i.count * i.price, 0))
  // 总的数量
  const allCount = computed(() => cartList.value.reduce((sum, item) => sum + item.count, 0))
  // 总价
  const allPrice = computed(() => cartList.value.reduce((sum, item) => sum + item.count * item.price, 0))
  // 是否全选
  const isAll = computed(() => cartList.value.every(item => item.selected))
  return {
    cartList,
    allCount,
    allPrice,
    allCheckCount,
    allCheckPrice,
    allCheck,
    singleCheck,
    addCart,
    delCart,
    clearCart,
    updateNewList,
    isAll
  }
}, {
  persist: true
})